# 采用 pandas操作 操作数据，  西瓜2.0数据
# 使用决策树（由于决策树不支持字符集）
# from sklearn.preprocessing import MultiLabelBinarizer
# 采用MultiLabelBinarizer处理字符集，转成 独热变量

from sklearn.tree import DecisionTreeClassifier
from sklearn import tree
from sklearn.model_selection import train_test_split
import numpy as np
from sklearn import metrics
from sklearn.metrics import confusion_matrix
import matplotlib.pyplot as plt
import pandas as pd
### 加载数据集 ######################
import pandas

# 数据读取 ############################################################
df = pandas.read_csv('melon2.0.csv')  #西瓜数据
print(df)
print(df.columns)

df = df.values
y_data = df[:, -1]
x_data = df[:, 1:-1]
print(x_data.shape, y_data.shape)
print(x_data, y_data)

# 属性值转独热标签 ############################################################
from sklearn.preprocessing import MultiLabelBinarizer
mlb = MultiLabelBinarizer()    # 把属性字段 化为独热变量
x_data = mlb.fit_transform(x_data)
print(x_data.shape, y_data.shape)
print(x_data)

# np.random.seed(2022)  # 固定随机种子  数量太少就不划分 训练集与测试集
# x_train, x_test, y_train, y_test = train_test_split(x_data, y_data, test_size=0.3)  # 随机抽取30%的测试集


### 建立决策树  ###########################################################
model = DecisionTreeClassifier(criterion="entropy")  # 采用信息熵 C4.5算法
model.fit(x_data, y_data)

tree.plot_tree(model) #图示决策树

# 把树形结构输出到pdf
# !pip install graphviz
# import graphviz
# from sklearn import tree
# dot_data = tree.export_graphviz(clf, out_file=None)
# graph = graphviz.Source(dot_data)
# graph.render("西瓜2.0数据集") # 生成 '决策树.pdf'


### 输出结果  #################################################################
score = model.score(x_data, y_data)#输出训练误差
print(score)


plt.show()
print('done')

